from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from django.views import View
import json

@method_decorator(csrf_exempt, name='dispatch')
class MutChatAPIView(View):
    def post(self, request):
        try:
            # 解析JSON请求体
            data = json.loads(request.body)
            
            # 获取消息列表
            messages = data.get('messages', [])
            
            # 验证消息格式
            if not messages or not isinstance(messages, list):
                return JsonResponse({'error': 'Invalid messages format'}, status=400)
            
            # 处理每条消息并去重
            response_messages = []
            seen_contents = set()  # 用于存储已见过的消息内容
            
            for message in messages:
                if 'role' in message and 'content' in message:
                    content = message['content']
                    # 检查内容是否已经存在
                    if content not in seen_contents:
                        seen_contents.add(content)
                        response_messages.append(message)
            
            # 返回响应
            return JsonResponse({
                'messages': response_messages,
                'status': 'success'
            })
            
        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON format'}, status=400)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)